package com.iye.puretennis.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.activity.TabsIndicatorActivity;
import com.iye.puretennis.custom.AccessCallBack;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.custom.UserInfoFragment;
import com.iye.puretennis.domain.Group;
import com.iye.puretennis.domain.UserInfo;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/25.
 */
public class MyJoinedGroupFragment extends TabFragment {

    public static final String TAG = "my_joined_group";

    private GroupParticipantsAdapter groupParticipantsAdapter;

    private Group group;

    private String groupGuid;

    private List<UserInfo> groupParticipants = new ArrayList<UserInfo>();


    @Override
    public void onCustomCreateView(LayoutInflater inflater) {
        Session session = Session.newSession();

        groupGuid = (String) session.get("groupGuid");

        ListView groupParticipantsListView = (ListView) mainView.findViewById(R.id.group_participants_list);

        groupParticipantsAdapter = new GroupParticipantsAdapter(R.layout.group_request_item, inflater);

        groupParticipantsListView.setAdapter(groupParticipantsAdapter);

        ImageButton actionButton = (ImageButton) mainView.findViewById(R.id.action_button);

        actionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupMenu(v, R.menu.joined_group_menu, new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int itemId = item.getItemId();
                        if (itemId == R.id.exit_menu) {
                            deleteGroup();
                        }
                        return true;
                    }
                });
            }
        });
    }


    private void removeParticipant(final UserInfo userInfo) {

        ServerAccessHelper.removeParticipant(userInfo.getGuid(), groupGuid, token.getToken(), new AccessCallBack() {
            @Override
            public void doCallBack() {
                fragmentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        groupParticipants.remove(userInfo);
                        groupParticipantsAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }

    private void deleteGroup() {
        ServerAccessHelper.deleteGroup(groupGuid, token.getToken(), new AccessCallBack() {
            @Override
            public void doCallBack() {
                goFragment(getSourceId(), MyGroupsFragment.TAG, MyGroupsFragment.class, null, false);

            }
        });
    }


    @Override
    public int getViewId() {
        return R.layout.myjoingroup;
    }

    @Override
    public int getSourceId() {
        return R.id.my_join_group;
    }

    @Override
    public void updateUI() {
        //render page
        new Thread(new Runnable() {
            @Override
            public void run() {
                group = ServerAccessHelper.loadGroup(groupGuid, token.getToken(), false);
                if (group != null) {
                    groupParticipants = group.getGroupParticipants();
                }
                getActivity().runOnUiThread(uiGroupUpdate);
            }
        }).start();
    }

    private Runnable uiGroupUpdate = new Runnable() {
        @Override
        public void run() {
            if (group != null) {
                renderGroup(group);
            }
        }
    };

    private void renderGroup(final Group group) {

        final String name = group.getName();

        headerText.setText(name);

        groupParticipantsAdapter.notifyDataSetChanged();
    }


    private class GroupParticipantsAdapter extends BaseAdapter {
        private int resource;//数据绑定在哪个资源界面上
        private LayoutInflater inflater;//布局填充器,可以使用xml文件来生成它的view对象
        private ViewCache viewCache;

        GroupParticipantsAdapter(int resource, LayoutInflater inflater) {
            this.resource = resource;
            this.inflater = inflater;
        }

        @Override
        public int getCount() {
            return groupParticipants.size();
        }

        @Override
        public Object getItem(int position) {
            return groupParticipants.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            HuaWenHuPoTextView nameView;

            ImageView avatarView;

            ImageButton requestButton;

            if (convertView == null) {
                convertView = inflater.inflate(resource, null);
                nameView = (HuaWenHuPoTextView) convertView.findViewById(R.id.requestBy_name);
                avatarView = (ImageView) convertView.findViewById(R.id.user_photo);
                requestButton = (ImageButton) convertView.findViewById(R.id.btn_request);
                viewCache = new ViewCache();
                viewCache.nameView = nameView;
                viewCache.avatarView = avatarView;
                viewCache.requestButton = requestButton;
                convertView.setTag(viewCache);
            } else {
                viewCache = (ViewCache) convertView.getTag();
                nameView = viewCache.nameView;
                avatarView = viewCache.avatarView;
                requestButton = viewCache.requestButton;
            }
            final UserInfo userInfo = groupParticipants.get(position);
            nameView.setText(userInfo.getNickname(token.getGuid()));
            final String userGuid = userInfo.getGuid();
            if (userGuid.equals(group.getOwnerGuid())) {
                nameView.setTextColor(getResources().getColor(R.color.gold));
            } else {
                nameView.setTextColor(getResources().getColor(R.color.white));
            }
            avatarView.setTag(userGuid);
            loadUserImage(userGuid, avatarView);
            final boolean request = userInfo.isRequest();
            if (request) {
                requestButton.setVisibility(View.VISIBLE);
            } else {
                requestButton.setVisibility(View.INVISIBLE);
            }

            final boolean isMe = userGuid.equals(token.getGuid());

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isMe) {
                        ((TabsIndicatorActivity) getActivity()).goTab(3);
                    } else {
                        Session session = Session.newSession();
                        session.put("userGuid",userGuid);
                        goFragment(getSourceId(), UserInfoFragment.TAG, UserInfoFragment.class, null, false);
                    }
                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    if (!isMe) {
                        showPopupMenu(view, R.menu.details_delete_menu, new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {

                                removeParticipant(userInfo);

                                return true;
                            }
                        });
                    }
                    return true;
                }
            });
            return convertView;
        }
    }

    private final class ViewCache {

        private HuaWenHuPoTextView nameView;

        private ImageView avatarView;

        private ImageButton requestButton;

    }
}
